package com.yiqi.zhiyuan.feature.login.view;

import android.content.Intent;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.suozhang.framework.framework.AM;
import com.suozhang.framework.framework.BaseActivity;
import com.suozhang.framework.utils.TextUtil;
import com.suozhang.framework.widget.PowerfulEditText;
import com.yiqi.zhiyuan.R;
import com.yiqi.zhiyuan.entity.bo.TabEntity;
import com.yiqi.zhiyuan.feature.login.contract.LoginContract;
import com.yiqi.zhiyuan.feature.login.dependencies.login.DaggerLoginComponent;
import com.yiqi.zhiyuan.feature.login.dependencies.login.LoginPresenterModule;
import com.yiqi.zhiyuan.feature.main.view.MainActivity;
import com.yiqi.zhiyuan.feature.mine.contract.MineContract;

import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;

import static com.yiqi.zhiyuan.framework.ZYConstants.TYPE_LOGIN_CODE;
import static com.yiqi.zhiyuan.framework.ZYConstants.TYPE_LOGIN_PWD;

public class LoginActivity extends BaseActivity implements OnTabSelectListener, LoginContract.View, TextWatcher {


    @BindView(R.id.tab_login_action)
    CommonTabLayout mTabLoginAction;
    @BindView(R.id.edt_login_pwd_phone)
    PowerfulEditText mEdtLoginPwdPhone;
    @BindView(R.id.edt_login_pwd_pwd)
    PowerfulEditText mEdtLoginPwdPwd;
    @BindView(R.id.edt_login_code_phone)
    PowerfulEditText mEdtLoginCodePhone;
    @BindView(R.id.edt_login_code_code)
    PowerfulEditText mEdtLoginCodeCode;
    @BindView(R.id.btn_login_code_send)
    TextView mBtnLoginCodeSend;
    @BindView(R.id.btn_login_register)
    TextView mBtnLoginRegister;
    @BindView(R.id.view_login_pwd)
    LinearLayout mViewLoginPwd;
    @BindView(R.id.view_login_code)
    LinearLayout mViewLoginCode;
    @BindView(R.id.btn_login_pwd)
    TextView mBtnLoginPwd;
    @BindView(R.id.btn_login_code)
    TextView mBtnLoginCode;

    @Inject
    LoginContract.Presenter mPresenter;


    private String[] mTitles = {"密码登录", "验证码登录"};

    private ArrayList<CustomTabEntity> mTabEntities = new ArrayList<>();

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_login;
    }

    @Override
    protected void initInjector() {
        DaggerLoginComponent.builder().loginPresenterModule(new LoginPresenterModule(this)).build().inject(this);
    }

    @Override
    protected void initView() {
        initTabData();
        setShowTab(0);
    }

    @Override
    protected void initData() {
        mBtnLoginRegister.setText(TextUtil.setTextViewColor(getString(R.string.login_no_account) + getString(R.string.register), getString(R.string.register), getResources().getColor(R.color.login_reset_pwd)));
    }

    @Override
    protected void initEvent() {
        mEdtLoginPwdPhone.addTextChangedListener(this);
        mEdtLoginPwdPwd.addTextChangedListener(this);

        mEdtLoginCodePhone.addTextChangedListener(this);
        mEdtLoginCodeCode.addTextChangedListener(this);
    }

    /***
     * 重置密码
     * */
    @OnClick(R.id.btn_login_reset)
    public void onViewResetClicked() {
        startActivity(new Intent(this, ForgetPasswordActivity.class));
    }

    /**
     * 密码登录
     **/
    @OnClick(R.id.btn_login_pwd)
    public void onViewPwdLoginClicked() {
        mPresenter.loginByPwd(mEdtLoginPwdPhone.getText().toString(), mEdtLoginPwdPwd.getText().toString(), TYPE_LOGIN_PWD);
    }

    /**
     * 验证码登录
     **/
    @OnClick(R.id.btn_login_code)
    public void onViewCodeLoginClicked() {
        mPresenter.loginByCode(mEdtLoginCodePhone.getText().toString(), mEdtLoginCodeCode.getText().toString(), TYPE_LOGIN_CODE);
    }

    /**
     * 还未注册，去注册
     */
    @OnClick(R.id.btn_login_register)
    public void onViewClicked() {
        startActivity(new Intent(this, RegisterActivity.class));
    }


    /**
     * 发送验证码
     */
    @OnClick(R.id.btn_login_code_send)
    public void onViewSendCodeClicked() {
        mPresenter.sendCode(mEdtLoginCodePhone.getText().toString().trim());
    }
    @Override
    public void onTabSelect(int position) {
        setShowTab(position);
    }

    @Override
    public void onTabReselect(int position) {

    }

    //切换登录方式
    private void setShowTab(int pos) {
        mViewLoginPwd.setVisibility(pos == 0 ? View.VISIBLE : View.GONE);
        mViewLoginCode.setVisibility(pos == 1 ? View.VISIBLE : View.GONE);
    }

    private void initTabData() {
        for (String mTitle : mTitles) {
            mTabEntities.add(new TabEntity(mTitle, 0, 0));
        }
        mTabLoginAction.setTabData(mTabEntities);
        mTabLoginAction.setOnTabSelectListener(this);
    }

    @Override
    public void showGetCodeSuccess() {
        onGetCode();
    }

    @Override
    public void showGetCodeError(String errorMsg) {
        showMsg(errorMsg);
    }

    @Override
    public void showLoginSuccess() {
        startActivity(new Intent(this, MainActivity.class));
        finish();
    }

    @Override
    public void showLoginError(String errorMsg) {
        showMsg(errorMsg);
    }

    public void onGetCode() {
        final int count = 60;//倒计时60秒
        Observable.interval(0, 1, TimeUnit.SECONDS)
                .take(count + 1)
                .map(new Function<Long, Long>() {
                    @Override
                    public Long apply(Long aLong) throws Exception {
                        return count - aLong;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())//ui线程中进行控件更新
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        mBtnLoginCodeSend.setEnabled(false);
                        mBtnLoginCodeSend.setTextColor(AM.res().getColor(R.color.text_secondary));
                    }
                }).subscribe(new Observer<Long>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(Long num) {
                mBtnLoginCodeSend.setText(num + "s");
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {
                //回复原来初始状态
                mBtnLoginCodeSend.setEnabled(true);
                mBtnLoginCodeSend.setText("获取验证码");
                mBtnLoginCodeSend.setTextColor(AM.res().getColor(R.color.primary_highlight));
            }
        });

    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
    }

    @Override
    public void afterTextChanged(Editable s) {
        if (!TextUtils.isEmpty(mEdtLoginPwdPhone.getText().toString().trim()) &&mEdtLoginPwdPhone.getText().toString().trim().length()==11&& !TextUtils.isEmpty(mEdtLoginPwdPwd.getText().toString().trim()) && mEdtLoginPwdPwd.getText().toString().trim().length() >= 6) {
            mBtnLoginPwd.setEnabled(true);
        } else {
            mBtnLoginPwd.setEnabled(false);
        }

        if (!TextUtils.isEmpty(mEdtLoginCodePhone.getText().toString().trim()) &&mEdtLoginCodePhone.getText().toString().trim().length()==11 && !TextUtils.isEmpty(mEdtLoginCodeCode.getText().toString().trim()) && mEdtLoginCodeCode.getText().toString().trim().length() == 6) {
            mBtnLoginCode.setEnabled(true);
        } else {
            mBtnLoginCode.setEnabled(false);
        }
    }


}
